<template>
  <details
    ref="el"
    :class="cn(dropdownVariants({ placement, modifier }))"
    :open="open"
    @toggle="onToggle"
  >
    <summary :class="cn(buttonClass)">
      <slot name="trigger">{{ label }}</slot>
    </summary>
    <div class="dropdown-content">
      <slot></slot>
    </div>
  </details>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { cva } from "class-variance-authority";
import { cn } from "@/components/utils";
import type { DropdownPlacement, DropdownModifier } from "./types";
import { onClickOutside } from "@vueuse/core";

interface Props {
  label?: string;
  buttonClass?: string;
  placement?: DropdownPlacement;
  modifier?: DropdownModifier;
}

withDefaults(defineProps<Props>(), {
  buttonClass: "btn",
});

const dropdownVariants = cva("dropdown", {
  variants: {
    placement: {
      top: "dropdown-top",
      bottom: "dropdown-bottom",
      left: "dropdown-left",
      right: "dropdown-right",
      start: "dropdown-start",
      center: "dropdown-center",
      end: "dropdown-end",
    },
    modifier: {
      hover: "dropdown-hover",
      open: "dropdown-open",
    },
  },
});

const open = ref(false);
const onToggle = (event: Event) => {
  open.value = (event.target as HTMLDetailsElement).open;
};
const el = ref();
onClickOutside(el, () => (open.value = false));
</script>
